package coder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class CoderServer {

    public static void main(String[] args) {
        //dev修改999
        //我是1.0版本
        //我是2.0版本
        ServerBootstrap boot =new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        NioEventLoopGroup group1 = new NioEventLoopGroup();
        try {
            boot.group(group,group1)
            .localAddress(9999)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new MyDoCoder());
                    channel.pipeline().addLast(new SimpleChannelInboundHandler<Integer>() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            System.out.println("有新连接");
                            ctx.writeAndFlush(ctx.alloc().buffer().writeInt(1));
                        }

                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Integer integer) throws Exception {
                            System.out.println(integer);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            cause.printStackTrace();
                            ctx.close();
                        }
                    });
                }
            })
            ;
            ChannelFuture future=  boot.bind().sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
            group1.shutdownGracefully();
        }

    }
}
